package cn.ljn.pet.service.impl;

import cn.ljn.pet.domain.PetType;
import cn.ljn.pet.mapper.PetTypeMapper;
import cn.ljn.pet.service.IPetTypeService;
import cn.ljn.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljn
 * @since 2023-03-13
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> tree() {
        ArrayList list = new ArrayList<>();
        List<PetType> petList = petTypeMapper.findAll();
        Map<Long, PetType> typeMap = petList.stream().collect(Collectors.toMap(PetType::getId, petType -> petType));
        petList.forEach(petType -> {
            if (petType.getPid() == null){
                list.add(petType);
            }else {
                PetType type = typeMap.get(petType.getPid());
                type.getChildren().add(petType);
            }
        });
        return list;
    }


}
